//
//  BIDExchangeListViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/12.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDExchangeListViewController.h"
#import "BIDPublishExchangeInfoViewController.h"
#import "BIDExchangeDetailViewController.h"
#import "BIDCategoryForExchangeCell.h"
#import "BIDGoodsForExchangeCell.h"
#import "BIDBaseListView.h"
#import "UITableView+BIDHaveEmptyData.h"
#import <SDWebImage/UIImageView+WebCache.h>

static NSString *categoryListURL = @"displaceTypeAndroid/list.action";
static NSString *goodsListURL = @"displaceAndroid/list.action";

@interface BIDExchangeListViewController ()<BIDBaseListViewDelegate>
{
    NSMutableArray *_dataSourceArr;
    NSMutableArray *_categoryArr;
    NSArray *_originalCategoryArr;
    BOOL _isRegister;
    NSUInteger _selectForCategoryIndex;
    NSMutableArray *_categoryStatus;
    NSUInteger _curPage;
    NSUInteger _countPerPage;
}
@end

@implementation BIDExchangeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"爱置换";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(publishExchangeInfoHandler)];
    //
    _dataSourceArr = [NSMutableArray array];
    _categoryArr = [NSMutableArray array];
    _originalCategoryArr = [[NSArray alloc] init];
    _selectForCategoryIndex = 0;
    _curPage = 0;
    _countPerPage = 15;
    _tableView.myDelegate = self;
    //
    [self getCategoryList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_dataSourceArr removeAllObjects];
    _curPage = 0;
    if(_categoryArr && _categoryArr.count>0)
    {
        [self getGoodsList];
    }
}

/**
 获取分类列表
 */
- (void)getCategoryList
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], categoryListURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@", [AppDelegate getUserId]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(id obj, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            if([obj isKindOfClass:[NSArray class]])
            {
                NSArray *arr = (NSArray *)obj;
                if(arr.count > 0)
                {
                    _originalCategoryArr = [[NSArray alloc] initWithArray:arr];
                    [_categoryArr addObject:@{@"name":@"全部", @"id":@"", @"selectStatus":@1}];
                    for(NSDictionary *dic in arr)
                    {
                        [_categoryArr addObject:@{@"name":dic[@"name"], @"id":dic[@"id"], @"selectStatus":@0}];
                    }
                }
                [_categoryTableView reloadData];
                //
                [self getGoodsList];
            }
        }
    }];
}

/**
 获取商品列表
 */
- (void)getGoodsList
{
    _curPage++;
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], goodsListURL];
    NSString *strPost = @"";
    NSString *strTypeID = _categoryArr[_selectForCategoryIndex][@"id"];
    if(_selectForCategoryIndex == 0)
    {
        strPost = [[NSString alloc] initWithFormat:@"page=%ld&rows=%ld", _curPage, _countPerPage];
    }
    else
    {
        strPost = [[NSString alloc] initWithFormat:@"searchParam.typeId=%@&page=%ld&rows=%ld", strTypeID, _curPage, _countPerPage];
    }
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            NSArray *arr = responseDic[@"rows"];
            if(arr.count > 0)
            {
                [_dataSourceArr addObjectsFromArray:arr];
                if(_dataSourceArr.count < _curPage*_countPerPage)
                {
                    [_tableView hasNoMoreData];
                }
                else
                {
                    [_tableView hasMoreData];
                }
            }
            [_tableView reloadData];
        }
        if(_dataSourceArr.count == 0)
        {
            [_tableView showEmptyView];
        }
        else
        {
            [_tableView hideEmptyView];
        }
    }];
}

/**
 发布置换信息
 */
- (void)publishExchangeInfoHandler
{
    BIDPublishExchangeInfoViewController *vc = [[BIDPublishExchangeInfoViewController alloc] initWithNibName:@"BIDPublishExchangeInfoViewController" bundle:nil];
    vc.categoryArr = [[NSArray alloc] initWithArray:_originalCategoryArr];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self setNavigationControllerAttribute:nav];
    [self presentViewController:nav animated:YES completion:^{}];
}

/**
 *  结束下拉刷新和上拉加载更多的旋转动画
 */
- (void)externalTask
{
    [_tableView endRefresh];
    [_tableView hasNoMoreData];
}

#pragma mark - BaseListViewDelegate
/**
 *  下拉刷新
 */
- (void)refresh
{
    NSLog(@"refresh");
    _curPage = 0;
    NSArray *arr = _dataSourceArr;
    if(arr.count>0)
    {
        if([arr[0] isKindOfClass:[NSArray class]] && arr.count>1)
        {
            //多个section
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, arr.count)];
            [_tableView beginUpdates];
            [_tableView deleteSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            [_dataSourceArr removeAllObjects];
            [_tableView endUpdates];
        }
        else
        {
            //只有一个section
            NSMutableArray *indexPathArr = [NSMutableArray array];
            for(int i=0; i<arr.count; i++)
            {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [indexPathArr addObject:indexPath];
            }
            [_tableView beginUpdates];
            [_dataSourceArr removeAllObjects];
            [_tableView deleteRowsAtIndexPaths:indexPathArr withRowAnimation:UITableViewRowAnimationAutomatic];
            [_tableView endUpdates];
        }
    }
    [self getGoodsList];
}
/**
 *  上拉加载更多
 */
- (void)loadMoreData
{
    [self getGoodsList];
}

#pragma mark - BaseListViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag == 1)
    {
        return _categoryArr.count;
    }
    else
    {
        return _dataSourceArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *categoryIdentifier = @"categoryIdentifier";
    static NSString *goodsIdentifier = @"goodsIdentifier";
    NSUInteger row = indexPath.row;
    if(!_isRegister)
    {
        _isRegister = YES;
        UINib *nib1 = [UINib nibWithNibName:@"BIDCategoryForExchangeCell" bundle:nil];
        [_categoryTableView registerNib:nib1 forCellReuseIdentifier:categoryIdentifier];
        UINib *nib2 = [UINib nibWithNibName:@"BIDGoodsForExchangeCell" bundle:nil];
        [_tableView registerNib:nib2 forCellReuseIdentifier:goodsIdentifier];
    }
    if(tableView.tag == 1)
    {
        //分类
        BIDCategoryForExchangeCell *categoryCell = [tableView dequeueReusableCellWithIdentifier:categoryIdentifier];
        NSDictionary *dic = _categoryArr[row];
        categoryCell.titleLabel.text = dic[@"name"];
        if(_selectForCategoryIndex == indexPath.row)
        {
            categoryCell.flagLabel.hidden = NO;
            categoryCell.titleLabel.textColor = [UIColor blackColor];
        }
        else
        {
            categoryCell.flagLabel.hidden = YES;
            categoryCell.titleLabel.textColor = RGBACOLOR(106.f, 106.f, 106.f, 1.f);
        }
        cell = categoryCell;
    }
    else if(tableView.tag == 2)
    {
        NSDictionary *dic = _dataSourceArr[row];
        //商品
        BIDGoodsForExchangeCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:goodsIdentifier];
        goodsCell.titleLabel.text = dic[@"title"];
        goodsCell.priceLabel.text = [[NSString alloc] initWithFormat:@"￥%@", ANY2NSSTRING(dic[@"price"])];
        NSString *strTime = dic[@"createTime"];
        NSDate *date = [BIDGlobalMethods transToNSDateByFormatter:@"yyyy-MM-dd HH-mm-ss" fromStringDate:strTime];
        goodsCell.timeLabel.text = [date timeIntervalDescription];
        //
        NSDictionary *picDic = nil;
        NSArray *fileArr = dic[@"fileList"];
        if(fileArr.count > 0)
        {
            picDic = fileArr[0];
            NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], picDic[@"path"]];
            [goodsCell.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"pic_placeholder.png"]];
        }
        else
        {
            [goodsCell.imgView setImage:[UIImage imageNamed:@"pic_placeholder.png"]];
        }
        cell = goodsCell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    if(tableView.tag == 1)
    {
        if(_selectForCategoryIndex != indexPath.row)
        {
            _selectForCategoryIndex = indexPath.row;
            [tableView reloadData];
            [_dataSourceArr removeAllObjects];
            _curPage = 0;
            [self getGoodsList];
        }
    }
    else
    {
        NSDictionary *dic = _dataSourceArr[row];
        BIDExchangeDetailViewController *vc = [[BIDExchangeDetailViewController alloc] initWithNibName:@"BIDExchangeDetailViewController" bundle:nil];
        vc.exchangeID = dic[@"id"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == 1)
    {
        return 44.f;
    }
    else
    {
        return 80.f;
    }
}

@end
